import axios from "axios";

import SingletonMessage from "@/utils/message";

const http = axios.create({
  baseURL: "/api",
  timeout: 20000,
  headers: {
    "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
  },
  withCredentials: true,
});

const Cookies =
  "mt_id=5267d5b48f834e18ac6cc983dca7ed48301c590a72cb411f; trackID=42f393e4-8ceb-4f76-8530-7a03f15d6b68; Hm_lvt_e01c7977efc0637a353637c0a1127bb6=1715092265,1715093366,1715146062,1715218903; Hm_lpvt_e01c7977efc0637a353637c0a1127bb6=1715218907;";

http.interceptors.request.use(
  (config) => {
    config.headers.Cookies = Cookies;
    return config;
  },
  (err) => Promise.reject(err)
);

const httpCode = {
  401: "请求访问未授权",
  404: "请求地址不存在，请联系管理员",
  500: "服务器错误，请联系管理员",
  default: "服务器连接失败",
};

http.interceptors.response.use(
  (res) => {
    return res.data.data || res.data;
  },
  (error) => {
    if (error.message === "Network Error") {
      SingletonMessage.error("后端接口连接异常");
    } else if (error.response === undefined) {
      return Promise.reject();
    } else if (error.message.includes("timeout")) {
      SingletonMessage.error("系统接口请求超时");
    } else {
      SingletonMessage.error(httpCode[error.response?.status || "default"]);
    }

    return Promise.reject(error);
  }
);

export default http;
